#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/8/30
# @USER    : Connor He
# @File    : test.py
# @Software: PyCharm
# @Version  : Python-
# @TASK:
from bmlib.core import BookmarksConverter
import copy

KEYS = ('type', 'title', 'children')


def merge_json(json_source, json_target):
    if json_source[KEYS[0]] == json_target[KEYS[0]] == 'folder':
        if json_source[KEYS[1]] == json_target[KEYS[1]]:
            print('Title: {}'.format(json_source[KEYS[1]]))

            json_source_child = json_source[KEYS[2]]
            json_target_child = json_target[KEYS[2]]
            extra_json = []
            idxs_source = list(range(len(json_source_child)))
            idxs_target = list(range(len(json_target_child)))
            while len(idxs_target) != 0:
                json_target_child_id = idxs_target.pop(0)
                json_target_child_one = json_target_child[json_target_child_id]
                flag = False
                for idx in idxs_source:
                    json_source_child_one = json_source_child[idx]
                    if merge_json(json_source_child_one, json_target_child_one):
                        flag = True
                        # print('existed: {}'.format(json_target_child_one[KEYS[1]]))
                        idxs_source.remove(idx)
                        break
                if not flag:
                    extra_json.append(json_target_child_one)
                    print('    new: {}'.format(json_target_child_one[KEYS[1]]))
            json_source_child.extend(extra_json)
            # json_source[KEYS[2]].extend(extra_json)
            return True
        else:
            return False
    elif json_source[KEYS[0]] == json_target[KEYS[0]] == 'url':
        if json_source[KEYS[1]] == json_target[KEYS[1]]:
            return True
        else:
            return False
    else:
        return False


def main():
    src = '../data/bookmarks_2025_11_16.html'
    dst = '../data/bookmarks_2025_11_18.html'
    src, dst = dst, src
    bookmarks = BookmarksConverter(src)
    bookmarks.parse('html')
    bookmarks.convert('json')
    # bookmarks.convert('html')
    # bookmarks.save()
    json_bm = bookmarks.bookmarks


    bookmarks2 = BookmarksConverter(dst)
    bookmarks2.parse('html')
    bookmarks2.convert('json')
    json_bm2 = bookmarks2.bookmarks

    if merge_json(json_bm, json_bm2):
        bookmarks.bookmarks = json_bm
        # bookmarks.convert('html')
        json_file = bookmarks.save()

        bookmarks3 = BookmarksConverter(json_file)
        bookmarks3.parse('json')
        bookmarks3.convert('html')
        print(bookmarks3.save())
    pass


def main2():
    from bmlib.json_to_html import json2html
    json_file = '../data/output_bookmarks_chrome_001.json'
    save_file = './temp.html'
    json2html(json_file, save_file)
    pass


if __name__ == '__main__':
    # main2()
    main()
    print('done')
